Java.lang Package

In this module you will learn……

·         Introduction to Java.lang package

·         Object class

·         Interfaces available in the package

·         Number class

·         Math class

·         String class

·         StringBuffer class

·         Wrapper classes

·         System class

·         Throwable class

·         Class class

·         ClassLoader class

 

Introduction to Java.lang Package

 

The java.lang package contains classes that are central in operation of the Java language and environment .This package is included by default by the Java compiler for every source file .This chapter examines some of the most important classes of the java.lang package.

·                     Object

·                     Math

·                     The wrapper classes

·                     String

·                     StringBuffer

 

The interfaces that will be covered are

·                     Cloneable

·                     Comparable

·                     Runnable

 

The Partial hierarchy in  the Java.lang package

 

                                                                Object

 

 

              Boolean     Character    Void     Number    Math    String     StringBuffer

 

 


                       Byte     Short      Integer   Long   Float  Double

 

 

public class Object 

The Object class is the super class of  all the classes .All classes including arrays inherit the methods of the Object class.

 

Method Summary

Protected Object

clone()
Creates and returns a copy of this object.

Boolean

equals(Object obj)
Indicates whether some other object is "equal to" this one.

Protected void

finalize()
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Class

getClass()
Returns the runtime class of an object.

 

int

hashCode()

Returns a hash code value for the object.

void

notify()
Wakes up a single thread that is waiting on this object's monitor.

void

notifyAll()
Wakes up all threads that are waiting on this object's monitor.

String

toString()
Returns a string representation of the object.

void

wait()
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

void

wait (long timeout)
Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

void

wait (long timeout, int nanos)
Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

 

 

public Interface Cloneable

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Attempts to clone instances that do not implement the Cloneable interface result in the exception CloneNotSupportedException being thrown.

The interface Cloneable declares no methods.

 

public Interface Comparator

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. It is strongly recommended (though not required) that natural orderings be consistent with equals else they have a very strange behaviour when comparisons are made. A class's natural ordering is said to be consistent with equals if and only if (e1.compareTo((Object)e2)==0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 of class C.

 

The only method that it contains is  the  int compareTo(Object obj).This method takes a parameter of type Object and compares it to the other object and returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

 

public Interface Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run. The Runnable interface is implemented by the class Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods.

The only method that it contains is the public void run().When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

 

public abstract class Number

 The abstract class Number is the superclass of classes Byte, Double, Float, Integer, Long, and Short.

Methods

byte byteValue()          : Returns the byte value of the specified number.

abstract  double doubleValue(): Returns the double value of the specified number.

abstract float floatValue(): Returns the float value of the specified number.

abstract  int intValue()  : Returns the integer value of the specified number.

abstract long longValue(): Returns the long value of the specified number.

short shortValue(): Returns the short value of the specified number.

 

 

 

 

public final class Math

The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. All methods in the  Math class are static.

 

Fields

static double E : The double value that is closer than any other to e, the base of the natural logarithms.

static double PI : The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.

 

Methods

static double abs(double a)  :Returns the absolute value of a double value.

 

static int abs(int a)  :Returns the absolute value of an integer value.

 

static float abs(float a) :Returns the absolute value of a float value.

 

static double cos(double a ): Returns the trigonometric cosine of the angle.

 

static double sin(double a ): Returns the trigonometric sine of the angle.

 

static double tan(double a ): Returns the trigonometric tan of the angle.

 

static double ceil(double a): Returns the smallest double value that is not less than the argument is equal to the nearest integer.

 

static double floor(double d): Returns the largest integer which is not greater than d as a double value.

 

static int round(float f): Returns the closest integer to f.

 

static sqrt(double d): Returns the square root of d.

 

public final class String

 

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Strings are constant; their values cannot be changed after they are created. Because String objects are immutable they can be shared.

Example:

     String str = "abc";

is equivalent to:

 char data[] = {'a', 'b', 'c'};

 String str = new String(data);

 

Every string literal is represented internally by an instance of the String .Java classes may have a pool of such strings . When a literal is compiled the compiler adds an appropriate string to the pool . However if the same literal  already appeared as a literal elsewhere in the class then it is already represented in the pool .The compiler does not create a new copy ; instead it uses the already existing copy. This saves on memory and can do no harm. Since strings  are immutable there is no way that a piece of code can harm another piece of code by modifying a shared string.

Example:

1. String s1=”Compare”;

2. String s2=”Compare”;

3. if (s1.equals(s2))

{

            do something;

}

                       

                        s1

Oval: Compare 

 


                                   

 

                        s2

                                                Pool of literal strings     

The test at line three succeeds as the equals method checks the contained collection of characters.           

1. String s1=”Compare”;

2. String s2=”Compare”;

3. if (s1.equals(s2))

{

            do something;

}

The test at line 3 succeeds because s2 refers to the String pool that was created at line 1.

You can construct a String by explicitly calling the constructor.

String s2=new String(“Compare”);

At runtime a fresh instance of string is constructed duplicating the string in the literal pool . Finally , a reference to the new String is assigned to s2.

 

      String s2=new String( )

 

Oval: Compare Oval: Compare
 


           

 

            Program Space                                                 Pool of literals

The above figure shows that calling explicitly new String() results in existence of two objects one in the literal pool and the other in the program space.

The most important thing to remember is that the original string is never modified .What really happens is that a new string is created and is returned.

Example:

class StringOperation

{

  public static void main(String args[])

 {

   String s=”Strings”;

    s.concat(“are immutable”);

   System.out.println(s);

 }

                         }

The output of the above code is : Strings .Surprisingly it is not “Strings are immutable” .This is so because a new String is returned which can be stored in the same String object or in a different String object.

Example:

class StringOperation

{

  public static void main(String args[])

 {

   String s=”Strings”;

    s=s.concat(“are immutable”);

   System.out.println(s);

  }

}

Now you can well guess ,the output will be “Strings are immutable”.

 

Methods

char charAt(int index):This returns the indexed character of the string ,where the index of the initial character is 0.

String concat(String s):This returns a new string  consisting of the old string followed by s.

boolean endsWith(String suffix):This returns true if the string ends with the specified suffix else returns false.

boolean equals(Object ob):This returns true if ob instance of String and the string encapsulated in ob matches the string encapsulated by the executing object.

boolean equalsIgnoreCase(String s):This is like equals(),but the argument is a String, and the comparison ignores case.

int indexOf(char ch): This returns the index of the first occurrence of the character in the string

int lastIndexOf(char ch):This returns the index of  the last occurrence of the character in the string.

String replace(char oldChar, char newChar):This returns a new string generated by the oldChar by a newChar.

String subString(int startIndex): Returns the substring beginning at startIndex and extending to the end of the string.

String trim():This returns the string that results from removing whitespace characters from the beginning and ending of  the current string.

 

public final class StringBuffer

A string buffer implements a mutable sequence of characters. A string buffer is like a String but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are used by the compiler to implement the binary string concatenation operator +.

Example:

     x = "a" + 4 + "c"

is compiled to the equivalent of:

     x = new StringBuffer().append("a").append(4).append("c")

                           .toString()

which creates a new string buffer (initially empty), appends the string representation of each operand to the string buffer in turn, and then converts the contents of the string buffer to a string. Overall, this avoids creating many temporary strings.

Constructors

StringBuffer(): Constructs an  empty string buffer with initial capacity of 16.

StringBuffer(int capacity):This constructs an empty string buffer with the specified capacity.

StringBuffer(String initial String):This constructs a string buffer that initially contains the specified string.

Methods:

StringBuffer append(String str):This appends str to the current stringbuffer.

StringBuffer append(Object obj):This calls toString() on the object and appends it to the StringBuffer.

StringBuffer insert(int offset, String str):This inserts str into the current string buffer at position offset.

StringBuffer reverse():This reverses the characters of  the current string buffer.

Example

StringBuffer sbuf =new StringBuffer(“12345”);

sbuf.reverse();              //”54321”

sbuf.insert(3,”aaa”);      //”543aaa21”

sbuf.append(“zzz”)        //”543aaa21zzz”

The method calls above actually modify the string buffer they operate on.

 

String concatenation the Easy Way

The concat() method of the String class and the append() method of the StringBuffer class glue two Strings together. An easier way to concatenate strings is to use Java’s overloaded + operator. String concatenation with + operator and arithmetic operations are situations in which Java provides built-in operator overloading.

This is how the technique works. If at compile time one of the operand is a String object then the + sign is interpreted as calling for string concatenation rather than arithmetic addition.

 

Example

"aaa" +" bbb" + "ccc";

The java compiler  treats the above code as if it were the following:

new StringBuffer().append(aaa).append(bbb).append(ccc).toString();

The conversion begins with an empty StringBuffer, then appends each element to it and finally calls the toString() method to convert the StringBuffer to a String.

 

Wrapper Classes

 

Each java primitive  data type has a corresponding wrapper class. A wrapper class is simply a class that  encapsulates a single immutable value. For example, the Integer class wraps up an int value, and the Float class encapsulates a float value. The wrapper classes do not perfectly match the corresponding primitive  data type names. The following table lists the primitives and wrappers. Except for the wrapper class Character all the other classes have the Number class as the abstract superclass.

 

Primitive Data Type                                             Wrapper Class

boolean                                                                       Boolean 

byte                                                                           Byte

char                                                                           Character

short                                                                           Short

int                                                                               Integer

long                                                                            Long

float                                                                             Float

double                                                                          Double  

 

All wrapper classes can be constructed by passing the value to be wrapped into the appropriate constructor.

 

Constructors

boolean   primitiveBoolean = true;

Boolean wrappedBoolean = new Boolean(primitiveBoolean);

byte   primitiveByte = 40;

Byte wrappedByte = new Byte(primitiveByte);

char   primitiveChar = ‘C’;

Character wrappedCharacter = new Character(primitiveCharacter);

short   primitiveShort = 31313;

Short wrappedShort = new Short(primitiveShort);

int  primitiveInteger = 4232424;

Integer wrappedInteger = new Integer(primitiveInteger);

float   primitiveFloat = 1.22f;

Float wrappedFloat = new Float(primitiveFloat);

long   primitiveLong = 412135242424l;

Long wrappedLong = new Long(primitiveLong);

double   primitiveDouble = 1.23;

Double wrappedDouble = new Double(primitiveDouble);

 

Most of the constructors throw NumberFormatException. Only Boolean does not throw this exception.

 

Methods

The value of any wrapped number can be retrieved as any numeric type .the retrieval methods are:

public byte byteValue()

public short shortValue()

public int intValue()

public long longValue()

public float floatValue()

public double doubleValue()

All wrapper classes have a static method called valueOf(String s) that parses a string and constructs and returns a wrapper instance of the same type as the class whose method was called.

Example

Long.valueOf(23l) ;

The above statement creates an instance of the Long class that wraps the value 23.

 

 

public final class System

The System class contains several useful class fields and methods. It cannot be instantiated.

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined "properties"; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

Example

System.out.println(“System”);                //System

In the above statement  System is the class, out is  a field of the System class that returns an object of the PrintStream class and println() is a method of the PrintStream class.

 

Fields

static PrintStream err :The "standard" error output stream.

static InputStream in :The "standard" input stream.

static PrintStream out :The "standard" output stream.

Methods

static void  arraycopy(Object src, int src_position, Object dst, int dst_position, int length) :Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.

static void exit (int status) :Terminates the currently running Java Virtual Machine.

static void gc() :Runs the garbage collector.

static void setSecurityManager(SecurityManager s): Sets the System security.

 

public class Throwable

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.

Instances of two subclasses, Error and Exception are conventionally used to indicate that exceptional situations have occurred.

Example:

 try {

         int a[] = new int[2];

         a[4];

      }

      catch (ArrayIndexOutOfBoundsException e) {

         System.out.println("exception: " + e.getMessage());

         e.printStackTrace();

     }

Constructor

Throwable() :Constructs a new Throwable with null as its error message string.

Throwable(String message) :Constructs a new Throwable with the specified error message.

 

Methods

String getMessage() :Returns the error message string of this throwable object.

void printStackTrace() :Prints this Throwable and its backtrace to the standard error stream.

String toString() :Returns a short description of this throwable object.

public final class Class

Instances of the class Class represent classes and interfaces in a running Java application. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.

Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

Example

The following example uses a Class object to print the class name of an object:

     void printClassName(Object obj) {

         System.out.println("The class of " + obj +

                            " is " + obj.getClass().getName());

     }

Methods

static Class forName (String className) :Returns the Class object associated with the class or interface with the given string name.

ClassLoader getClassLoader () :Returns the class loader for the class.

Constructor getConstructor(Class [] parameterTypes):Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Package getPackage () :Gets the package for this class.

Object newInstance(): Creates a new instance of the class represented by this Class object.

public abstract class ClassLoader

The class ClassLoader is an abstract class. A class loader is an object that is responsible for loading classes. Given the name of a class, it should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

 

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When called upon to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machine's built-in class loader, called the bootstrap class loader, does not itself have a parent but may serve as the parent of a ClassLoader instance.

 

Constructors

protected ClassLoader () :Creates a new class loader using the ClassLoader returned by the method getSystemClassLoader() as the parent class loader.

protected ClassLoader (ClassLoader parent) :Creates a new class loader using the specified parent class loader for delegation

 

Methods

protected Class findClass (String name) :Finds the specified class

protected String findLibrary (String libname) :Returns the absolute path name of a native library.

ClassLoader getParent ():Returns the parent class loader for delegation.

Class loadClass(String name) :Loads the class with the specified name.

 

 

Summary

·                     The java.lang package contains classes that are indispensable to Java’s   

              operation, so all  the classes of the package are imported automatically 

              into the source files.

·                     Some of the important classes in this package are:

·                     Object

·                     Math

·                     The Wrapper Classes

·                     String

·                     StringBuffer

·                     System

·                  All wrapper types are created from primitives ;all  but Character can also

             be created from strings.

·                  Wrapped values can be extracted with various XXXValue() methods.

·                  All the classes discussed above are final classes and hence they cannot be

             subclassed.

·                  Strings are immutable and hence are shareable.

·                  StringBuffers are mutable.

 

Test Your Knowledge

Q1. Which of the following classes is used to perform basic console I/O?

A)    System

B)     SecurityManager

C)     Math

D)    Runtime

 

Q2.Which of the following is not a Wrapper class?

      A)  String

      B)  Integer

      C) Boolean

      D) Character

 

 

Q3. What is wrong with the following code?

public class Question

{

  public static void main(String args[])

  {

     Boolean b = new Boolean(“True”);

        if(b)

       {

         for(Integer i=0;i<10;i++)

        {

          System.out.println(i);

        }

       }

    }

  }

A)  There is nothing wrong with this code.

B)  The if condition should be a boolean instead of a Boolean.

C)  The index of the for loop should be an int instead of an Integer.

D)  It is illegal to construct a Boolean.

 

Q4. What is the output of the following program?

 

public class Question

{

  public static void main(String args[])

  {

    String s1 = “abc”;

    String  s2 = “def”;

    String  s3 = s1.concat(s2.toUpperCase());

    System.out.println(s1+s2+s3);

  }

}

 

A)    abcdefabcdef.

B)     abcabcDEFDEF.

C)     abcdefabcDEF.

D)    None of the above.

 

Q5. Which of the following methods are methods of the Math class?

      A)  absolute()

      B)  log()

      C)  cosine()

      D)  sine()

 

Q6. Which of the following are true about the Error and Exception classes?

     A)  Both classes extend Throwable.

     B)  The Error class is final and the Exception class is not.

     C)  The Exception class is final and the Error class is not.

     D)  Both classes implement Throwable.

 

Q7. Which one statement is true about the code below?

1. String s1 = “abc”+”def”;

2. String s2 = new String(s1);

3. if(s1==s2)

4. System.out.println(“== succeeded”);

5. if(s1.equals(s2))

6. System.out.println(“.equals succeeded”);

 

A)   Lines 4 and 6 both execute

B)   Line 4 executes, and line 6 does not

C)   Line 6 executes, and line 4 does not.

D)   Neither line 4 nor line 6  executes

 

Q8.Which one statement is true about the code segment below?

1. import java.lang.Math;

2. Math myMath = new Math();

3. System.out.println(“cosine of 0.123 = “ +_myMath.cos(0.123));

 

A)    Compilation fails at line 2.

B)     Compilation fails at line 3.

C)     Compilation succeeds although exception is thrown at runtime

D)    Compilation succeeds and no exception is thrown during execution.

 

Q9. In code segment below is line 4 executed?

A)    String s1 = “xyz”;

B)     String s2 = “xyz”;

C)     if(s1==s2)

D)    System.out.println(“Line 4”);

 

Q10. In code segment below is line 4 executed?

A)    String s1 = “xyz”;

B)     String s2 = new String(s1);

C)     if(s1==s2)

D)    System.out.println(“Line 4”);

Exercises

·                     Design an Anagram  game using  the methods of the String

             class.

             Hint: In the  anagram game you have to guess the right word given 

             the jumbled version of the word.

·                     Check whether a given String is a palindrome or not.

·                     Given two sides of a right  angled triangle calculate the third side.